package com.supreme.commonnetty.server;

import com.supreme.commonnetty.server.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.PreDestroy;
import java.util.Optional;

@Lazy
@Configuration
public class NettyEchoServer {

    private NioEventLoopGroup acceptEventExecutors;
    private NioEventLoopGroup workerEventExecutors;

    public void startServer(int serverPort) {
        acceptEventExecutors = new NioEventLoopGroup(1);
        workerEventExecutors = new NioEventLoopGroup(1);

        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(acceptEventExecutors, workerEventExecutors)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new EchoServerHandler());
                    }
                });

        try {
            Channel channel = serverBootstrap.bind(serverPort).sync().channel();
            System.out.println("NettyEchoServer isActive: " + channel.isActive());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void nettyServerDestroy() {
        Optional.ofNullable(acceptEventExecutors).ifPresent(NioEventLoopGroup::shutdownGracefully);
        Optional.ofNullable(workerEventExecutors).ifPresent(NioEventLoopGroup::shutdownGracefully);
    }
}
